<template>
  <view class="container">
    <view class="cd-bg">
      <!-- 基本信息 -->
      <view class="cd-title">
        <uni-row>
          <uni-col :span="20">
            <view class="param">基本信息</view>
          </uni-col>
          <uni-col :span="4">
            <view class="param" v-if="detail.sta == 0 && detail.chexiao == 0">
              <uni-tag text="审核" type="warning"></uni-tag>
            </view>
            <view class="param" v-if="detail.sta == 1 && detail.chexiao == 0">
              <uni-tag text="通过" type="primary"></uni-tag>
            </view>
            <view class="param" v-if="detail.sta == 2 && detail.chexiao == 0">
              <uni-tag text="拒绝" type="error"></uni-tag>
            </view>
            <view class="param" v-if="detail.chexiao == 1">
              <uni-tag text="撤销" type="default"></uni-tag>
            </view>
          </uni-col>
        </uni-row>
      </view>
      <view class="cd-body">
        <view class="param">
          <b>申请人：</b>
          {{ detail.shenqingname }}
        </view>
        <view class="param">
          <b>申请部门：</b>
          {{ detail.departmentName }}
        </view>
        <view class="param">
          <b>申请时间：</b>
          {{ getFormatedTimeStr(detail.createTime) }}
        </view>
      </view>

      <!-- 特殊参数 -->
      <view class="cd-line">
        <view class="param">申请信息</view>
      </view>
      <view class="cd-body">
        <view class="param">
          <b>主题：</b>
          {{ detail.biaoti }}
        </view>
      </view>

      <!-- 相关图片 -->
      <view class="cd-line">
        <view class="param">
          <b>相关图片</b>
        </view>
      </view>
      <view class="cd-body">
        <!-- 附件 -->
        <view class="param">
          <b>图片：</b>
        </view>
        <uni-row>
          <uni-col :span="8" v-for="(it, idx) in detail.tupianUrl" :key="idx">
            <view class="img-res" @click="showBigImg(detail.tupianUrl, idx)">
              <image :src="detail.tupianUrl[idx]" :key="idx" />
            </view>
            <!-- <view class="file_list_item">
              <uni-link
                :href="it.url"
                :text="it.name"
                fontSize="16"
                color="#51bb88"
                showUnderLine="false"
              ></uni-link>
            </view>-->
          </uni-col>
        </uni-row>
      </view>
      <!-- 相关附件 -->
      <view class="cd-line">
        <view class="param">
          <b>相关附件</b>
        </view>
      </view>
      <view class="cd-body">
        <!-- 附件 -->
        <view class="param">
          <b>附件：</b>
        </view>
        <view v-for="(it, idx) in detail.url" :key="idx">
          <view @click="prevFileClick(it)" class="file_list_item">
            <view>
              <i
                class="iconfont icon-24gf-folderOpen"
                style="color: #0b847b"
              ></i>
              {{ it.name }}
            </view>
          </view>
          <!-- <view class="file_list_item">
              <uni-link
                :href="it.url"
                :text="it.name"
                fontSize="16"
                color="#51bb88"
                showUnderLine="false"
              ></uni-link>
          </view>-->
        </view>
      </view>

      <!-- 审核进度 -->
      <view class="cd-line">
        <view class="param">
          <b>审核进度</b>
        </view>
      </view>
      <!-- 承办进度 -->
      <view class="cd-body">
        <view
          v-for="(audi, idx) in detail.approvalProcessDataBeanMap"
          :key="idx"
        >
          <uni-row v-if="idx!==0">
            <uni-col :span="24">
              <view class="step-arrow">
                <uni-icons type="bottom" size="30" color="#a5eaff"></uni-icons>
              </view>
            </uni-col>
          </uni-row>
          <view class="step">
            <view class="step-title">
              <uni-row>
                <uni-col :span="8" style="display: flex">
                  <view class="step-title-left">{{ audi.name }}</view>
                  <view
                    style="text-align: right; color: #0b847b"
                    @click="urgingBtn(audi, idx)"
                    v-if="urgingInedx == idx"
                  >
                    <uni-icons
                      type="paperplane-filled"
                      color="#0b847b"
                      size="16"
                    ></uni-icons>
                    催办
                  </view>
                </uni-col>
                <uni-col :span="8">
                  <view class="step-title-center">
                    <uni-tag
                      text="未审核"
                      size="mini"
                      type="default"
                      v-if="audi.sta == 0"
                    ></uni-tag>
                    <uni-tag
                      text="同意"
                      size="mini"
                      type="primary"
                      v-if="audi.sta == 1"
                    ></uni-tag>
                    <uni-tag
                      text="拒绝"
                      size="mini"
                      type="error"
                      v-if="audi.sta == 2"
                    ></uni-tag>
                    <uni-tag
                      text="撤销"
                      size="mini"
                      type="default"
                      v-if="audi.sta == 3"
                    ></uni-tag>
                  </view>
                </uni-col>
                <uni-col :span="8">
                  <view class="step-title-right">{{ audi.stepName }}</view>
                </uni-col>
              </uni-row>
            </view>
            <view class="step-info">
              <uni-row>
                <uni-col :span="16" v-if="audi.sta > 0 && audi.msg == ''">
                  <view class="msg"> <b>意见：</b>无 </view>
                </uni-col>
                <uni-col :span="16" v-if="audi.sta > 0 && audi.msg != ''">
                  <view class="msg">
                    <b>意见：</b>
                    {{ audi.msg }}
                  </view>
                </uni-col>
                <uni-col :span="8" v-if="audi.sta > 0">
                  <view class="img-qm">
                    <image :src="audi.signimg" />
                  </view>
                </uni-col>
              </uni-row>
            </view>
            <view class="step-footer">
              <uni-row>
                <uni-col :span="24" v-if="audi.sta > 0">
                  <view class="step-footer-right">{{
                    getFormatedTimeStr(audi.ts)
                  }}</view>
                </uni-col>
              </uni-row>
            </view>
          </view>
        </view>
      </view>
      <view class="cd-line" v-if="approval1 > 0">
        <view class="param">
          <b>承办进度</b>
        </view>
      </view>
      <view class="cd-body" v-if="approval1 > 0">
        <view v-for="(cbr, idx, id) in this.approval2" :key="idx">
          <uni-row v-if="idx==1" style="margin-top:10px">
            <uni-col :span="24">
              <view class="param">
                <b>具体承办人</b>
              </view>
            </uni-col>
          </uni-row>
          <view v-if="id > 0" style="padding: 10px"></view>
          <view class="step">
            <view class="step-title-warn">
              <uni-row>
                <uni-col :span="8">
                  <view class="step-title-left">{{ cbr.name }} </view>
                </uni-col>
                <uni-col :span="8">
                  <view class="step-title-center">
                    <uni-tag
                      text="未完成"
                      size="mini"
                      type="default"
                      v-if="cbr.sta == 0"
                    ></uni-tag>
                    <uni-tag
                      text="完成"
                      size="mini"
                      type="primary"
                      v-if="cbr.sta == 1"
                    ></uni-tag>
                  </view>
                </uni-col>
                <uni-col :span="8">
                  <view class="step-title-right">
                    {{ cbr.stepName }}
                  </view>
                </uni-col>
              </uni-row>
            </view>
            <view class="step-info">
              <uni-row>
                <uni-col :span="24" v-if="cbr.sta > 0 && cbr.msg == ''">
                  <view class="msg"> <b>回复：</b>无 </view>
                </uni-col>
                <uni-col :span="24" v-if="cbr.sta > 0 && cbr.msg != ''">
                  <view class="msg">
                    <b>回复：</b>
                    {{ cbr.msg }}
                  </view>
                </uni-col>
              </uni-row>
            </view>
            <view class="step-footer">
              <uni-row>
                <uni-col :span="24" v-if="cbr.sta > 0">
                  <view class="step-footer-right">{{
                    getFormatedTimeStr(cbr.ts)
                  }}</view>
                </uni-col>
              </uni-row>
            </view>
          </view>
        </view>
      </view>
      <!-- 操作按钮 -->
      <view style="padding: 30px"></view>
      <view class="cd-footer" v-if="see == 1 && isMyAgree() == 1">
        <button @click="clickAudit(0)" type="primary">审批</button>
      </view>
      <view class="cd-footer" v-if="approval1 == 1 && isMyAgreeChengban() == 1">
        <button @click="clickAudit(1)" type="warn">承办</button>
      </view>
      <view class="cd-footer" v-if="see == 1 && isMyAgree() == 1">
        <button @click="revert()" type="warn">撤销</button>
      </view>

      <!-- <view class="cd-footer" v-if="see == 1 && isMyAgreeChengban() == 1">
        <button @click="clickShoucang" type="warn">{{shoucangBtnStr}}</button>
      </view>-->
    </view>
  </view>
</template>

<script>
import { websock } from "../../net/websock";
import {
  prevFile, // 预览普通文件
} from "../../utils/preview.js";
import { getxuanchaun } from "../../net/xuanchuanbaodao";
import moment from "moment";
import { getUserList, urgingFlowApi } from "../../net/xinjianfawen";
import { shenpixuanchuan } from "../../net/xuanchuanbaodao";
export default {
  data() {
    return {
      urgingInedx: null,
      id: 0,
      taskid: 0,
      see: 0,
      itemsd: "",
      itemssd: "",
      taskInfo1: [],
      approval: [],
      approval1: "",
      approval2: [],
      contents: {},
      taskInfo: {},
      detail: {},
      userInfo: {},
      approvalProcessDataBeanMaps: {},
      undertakeProcessDataMaps: {},
    };
  },
  async onReady() {
    try {
      this.userInfo = await websock.getUserInfo();
    } catch (e) {
      uni.showToast({
        title: e.message,
      });
    }
  },

  async onLoad(params) {
    console.log(params);
    if (params.content) {
      this.id = params.id;
      let arr = [];
      this.itemssd = params.itemss;
      this.contents = JSON.parse(params.content);
      console.log(JSON.parse(params.content));
      let chakan = JSON.parse(params.content);
      this.detail.auditors = chakan;
      this.approval1 = JSON.parse(params.content).undertakeState;
      this.approval2 = JSON.parse(params.content).undertakeProcessDataMap;

      this.detail.shenqingname = chakan.createBy; //申请人
      this.detail.createTime = chakan.createTime; //申请时间
      this.detail.departmentId = chakan.departmentId; //部门id
      const res = await websock.getDepartList();
      res.forEach((item) => {
        if (item.id == chakan.departmentId) {
          this.detail.departmentName = item.name;
        }
      });

      this.detail.biaoti = chakan.title; //标题
      chakan.imgAccessoryBeans.forEach((item) => {
        arr.push(item.url);
      });

      this.detail.tupianUrl = arr; //图片
      this.detail.url = chakan.accessoryBeans; //附件
      // this.detail.url = chakan.accessoryBeans; //附件

      this.approvalProcessDataBeanMaps = chakan.approvalProcessDataBeanMap;
      this.detail.approvalProcessDataBeanMap = Array.from(
        Object.values(chakan.approvalProcessDataBeanMap),
        (x) => x
      );
      this.approval = Array.from(
        Object.values(chakan.approvalProcessDataBeanMap),
        (x) => x
      );
      console.log(this.detail.approvalProcessDataBeanMap);
      // 判断可以催办哪个人
      this.canUrge(this.detail.approvalProcessDataBeanMap);
    } else {
      this.id = params.id;
      this.taskid = params.taskid;
      this.see = params.see || 0;
      this.itemsd = params.items;
      console.log("onload", params);
      this.getInfo();
      if (!params.ta) {
        this.taskInfo = await websock.getTaskDetail({ id: params.taskid });
        console.log(this.taskInfo);
      }
      this.taskInfo1 = await getUserList();
      console.log("task info", this.taskInfo1);
    }
  },
  methods: {
    // 判断可以催办哪个人
    canUrge(map) {
      const userId = JSON.parse(uni.getStorageSync("loginUserInfo")).uid;

      for (let i = 0; i < map.length; i++) {
        let item = map[i];
        if (item.sta == 0) {
          if (item.uid != userId) {
            this.urgingInedx = i;
          }
          break;
        } else if (item.sta == 2 || item.sta == 3) {
          this.urgingInedx = null;
          return;
        }
      }
    },
    // 催办
    urgingBtn(audi, idx) {
      let data = {
        taskId: this.detail.id ? this.detail.id : this.id,
        position: idx,
        userId: audi.uid,
        type: "3",
      };
      urgingFlowApi(data)
        .then((res) => {
          if (res.code === 0) {
            uni.showToast({
              title: "催办成功",
            });
          } else {
            uni.showToast({
              title: "催办失败",
              icon: "error",
            });
          }
        })
        .catch((err) => {
          console.log(err);
          uni.showToast({
            title: "催办失败",
            icon: "error",
          });
        });
    },

    prevFileClick(item) {
      prevFile(item);
    },
    async getInfo() {
      console.log(this.id, this.taskid);
      const id = this.id;
      const taskid = this.taskid;
      // console.log(id, taskid);
      let arr = [];
      const res = await getxuanchaun(id);
      console.log(res.data);
      this.approval1 = res.data.propagandaReport.undertakeState;
      this.detail = res.data;
      this.detail.shenqingname = res.data.propagandaReport.createBy; //申请人
      this.detail.createTime = res.data.propagandaReport.createTime; //申请时间
      this.detail.departmentId = res.data.propagandaReport.departmentId; //部门id
      const res1 = await websock.getDepartList();
      res1.forEach((item) => {
        if (item.id == res.data.propagandaReport.departmentId) {
          this.detail.departmentName = item.name;
        }
      });
      this.detail.biaoti = res.data.propagandaReport.title; //标题
      res.data.propagandaReport.imgAccessoryBeans.forEach((item) => {
        arr.push(item.url);
      });

      this.detail.tupianUrl = arr; //图片
      // this.detail.tupianUrl = res.data.propagandaReport.imgAccessoryBeans; //图片
      this.detail.url = res.data.propagandaReport.accessoryBeans; //附件
      this.approvalProcessDataBeanMaps =
        res.data.propagandaReport.approvalProcessDataBeanMap;
      this.undertakeProcessDataMaps =
        res.data.propagandaReport.undertakeProcessDataMap;

      this.detail.approvalProcessDataBeanMap = Array.from(
        Object.values(res.data.propagandaReport.approvalProcessDataBeanMap),
        (x) => x
      );
      // 判断可以催办哪个人
      this.canUrge(this.detail.approvalProcessDataBeanMap);

      this.detail.propagandaReport.undertakeProcessDataMap = Array.from(
        Object.values(res.data.propagandaReport.undertakeProcessDataMap),
        (x) => x
      );

      this.approval = Array.from(
        Object.values(res.data.propagandaReport.approvalProcessDataBeanMap),
        (x) => x
      );
      this.approval2 = Array.from(
        Object.values(res.data.propagandaReport.undertakeProcessDataMap),
        (x) => x
      );

      console.log(this.approval);
      for (let key in this.detail.auditors) {
        websock
          .getUserInfoByUid({
            uid: this.detail.auditors[key].uid,
          })
          .then((res) => {
            this.detail.auditors[key].name = res.name;
            this.detail.auditors[key].signimg = res.signimg;
          });
      }
    },

    async clickShoucang() {
      try {
        if (this.detail.shoucang) {
          await websock.cancelShoucang({
            id: this.detail.id,
            typ: 18,
          });
          this.detail.shoucang = 0;
        } else {
          await websock.shoucangGongwen({
            id: this.detail.id,
            typ: 18,
            title: this.detail.biaoti,
            content: this.detail.zhaiyao,
          });
          this.detail.shoucang = 1;
        }
      } catch (err) {
        console.error(err);
        uni.showToast({
          title: err.message || "error",
        });
      }
    },
    // 进行审批
    clickAudit(typ) {
      uni.navigateTo({
        url: `/pages/common/audit3?taskid=${this.taskid}&typ=${typ}&id=${
          this.id
        }&approvalProcessDataBeanMap=${JSON.stringify(
          this.approvalProcessDataBeanMaps
        )}&undertakeProcessDataMap=${JSON.stringify(
          this.undertakeProcessDataMaps
        )}`,
      });
    },
    // 判断我是不是审批过
    isMyAgree() {
      console.log(this.approval);
      let myid = this.userInfo.uid;
      console.log(myid);
      let arr = [];
      // console.log(res);
      for (let key in this.approval) {
        if (this.approval[key].uid == myid && this.approval[key].sta == 0) {
          return 1;
        } else if (this.approval[key].sta == 0) {
          arr.push(this.approval[key].sta);
        }
      }
      console.log(arr.length, this.approval.length);
      if (arr.length == this.approval.length) {
        return 2;
      } else {
        return 0;
      }
      // return 0;
    },
    // 判断我是不是承办过
    isMyAgreeChengban() {
      console.log(this.approval2);
      let myid = this.userInfo.uid;

      for (let key in this.approval2) {
        if (this.approval2[key].uid == myid && this.approval2[key].sta == 0) {
          return 1;
        }
      }
      return 0;
    },
    // 获取格式化时间字符串
    getFormatedTimeStr(stamp, str = "MM-DD HH:mm:ss") {
      return moment(stamp).format(str);
    },

    //点击放大U图片
    showBigImg(imgurl, cur) {
      uni.previewImage({
        current: cur,
        loop: true,
        urls: imgurl,
      });
    },
    shoucangBtnStr() {
      if (this.detail.shoucang) return "取消收藏";
      return "收藏";
    },
    async revert() {
      console.log(this.approvalProcessDataBeanMaps);
      this.approvalProcessDataBeanMaps = Array.from(
        Object.values(this.approvalProcessDataBeanMaps),
        (x) => x
      );
      console.log(this.approvalProcessDataBeanMaps);
      const timestamp = new Date().getTime();
      this.approvalProcessDataBeanMaps.forEach((data) => {
        console.log(data.uid);
        console.log(uni.getStorageSync("userInfo").uid);
        if (data.uid == this.taskInfo.uid) {
          data.msg = this.msg;
          data.sta = 3;
          data.ts = timestamp;
        }
      });
      console.log(this.approvalProcessDataBeanMaps);
      this.approvalProcessDataBeanMaps.forEach((names) => {
        this.taskInfo1.data.userList.forEach((item) => {
          if (item.uid == names.uid) {
            names.signimg = item.signimg;
          }
        });
      });
      let OldObject = this.approvalProcessDataBeanMaps.reduce((o, n, i) => {
        o["auditor" + i] = {
          ts: n.ts,
          msg: n.msg,
          sta: n.sta,
          signimg: n.signimg,
          uid: n.uid,
          stepName: n.stepName,
          name: n.name,
        };
        return o;
      }, {});
      console.log(OldObject);
      // 新建事项
      const params = {
        id: this.id,
        taskId: this.taskid,
        approvalProcessDataBeanMap: OldObject,
      };
      try {
        await shenpixuanchuan(params);
        uni.$emit("TASK-REVERT", this.taskid);
        this.getInfo();
        setTimeout(
          () =>
            uni.navigateBack({
              delta: 1,
            }),
          uni.showToast({
            title: "撤销成功",
          }),
          100
        );
      } catch (err) {
        console.error(err);
      }
    },
  },
};
</script>

<style>
@import url("../common/detail.css");
</style>
